package com.tianji.remark.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.dto.LikeRecordFormDTO;
import com.tianji.remark.dto.LikedTimesDTO;
import com.tianji.remark.entity.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.LikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * @author 墨墨
 * @description 针对表【liked_record(点赞记录表)】的数据库操作Service实现
 * @createDate 2024-10-28 20:27:45
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord>
        implements LikedRecordService {

    private final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate redisTemplate;

    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
        // 1.获取当前登录用户的id
        Long userId = UserContext.getUser();

        // 2.判断是否是点赞 liked为true是点赞
        boolean flag = dto.getLiked() ? liked(userId, dto) : unliked(userId, dto);
        if (!flag) {
            // 说明点赞失败或者取消赞失败
            return;
        }

        // 3.基于redis统计该业务id下的总点赞数
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        Long totalLikeNum = redisTemplate.opsForSet().size(key);
        if (totalLikeNum == null) {
            return;
        }

        // 4.采用zset缓存点赞总数
        String bizTypeTotalLikeKey = RedisConstants.LIKE_COUNT_KEY_PREFIX + dto.getBizType();
        redisTemplate.opsForZSet().add(bizTypeTotalLikeKey, dto.getBizId().toString(), totalLikeNum);

    }

    @Override
    public Set<Long> getLikeStatusByBizIds(List<Long> bizIds) {
//        // 1.获取用户id
//        Long userId = UserContext.getUser();
//        // 2.查询点赞记录表 liked_status
//        List<LikedRecord> list = this.lambdaQuery()
//                .eq(LikedRecord::getUserId, userId)
//                .in(LikedRecord::getBizId, bizIds)
//                .list();
//        // 3.转为集合
//        Set<Long> likedBizIds = list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());
//        return likedBizIds;
//        // 1.获取用户
//        Long userId = UserContext.getUser();
//
//        // 2.循环bizIds
//        if (CollectionUtil.isEmpty(bizIds)) {
//            return CollUtils.emptySet();
//        }
//        Set<Long> retSet = new HashSet<>();
//        for (Long bizId : bizIds) {
//            String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
//            // 3.判断当前业务，当前用户是否点赞
//            Boolean member = redisTemplate.opsForSet().isMember(key, userId.toString());
//            if (member) {
//                // 4.将当前用户id存入新集合返回
//                retSet.add(bizId);
//            }
//        }
//        return retSet;

        // 1.获取登录用户id
        Long userId = UserContext.getUser();
        // 2.查询点赞状态
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });
        // 3.返回结果
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get)// 用角标i取bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toSet());// 收集
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        // 1.拼接key  like:times:type:QA  like:times:type:NOTE
        String bizTypeTotalLikeKey = RedisConstants.LIKE_COUNT_KEY_PREFIX + bizType;

        List<LikedTimesDTO> list = new ArrayList<>();
        // 2.从redis中zset中获取业务点赞信息  按照分数排序取小的
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(bizTypeTotalLikeKey, maxBizSize);
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String bizId = typedTuple.getValue();
            Double likedTimes = typedTuple.getScore();
            if (StringUtils.isBlank(bizId) || likedTimes == null) {
                continue;
            }
            // 3.封装LikedTimesDTO 消息数据
            LikedTimesDTO msg = LikedTimesDTO.builder()
                    .bizId(Long.valueOf(bizId))
                    .likedTimes(likedTimes.intValue())
                    .build();
            list.add(msg);
        }
        // 4.发送消息到MQ
        if (CollectionUtil.isNotEmpty(list)) {
            String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);
            log.debug("批量发送点赞消息：{}", list);
            rabbitMqHelper.send(
                    MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                    routingKey,
                    list
            );
        }

    }

    /**
     * 取消赞
     * @param userId
     * @param dto
     * @return
     */
    private boolean unliked(Long userId, LikeRecordFormDTO dto) {
        // 拼接key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        // redisTemplate添加点赞记录
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result != null && result > 0;
    }

    /**
     * 点赞
     * @param userId
     * @param dto
     * @return
     */
    private boolean liked(Long userId, LikeRecordFormDTO dto) {
        // 拼接key
        String key = RedisConstants.LIKE_BIZ_KEY_PREFIX + dto.getBizId();
        // redisTemplate添加点赞记录
        Long result = redisTemplate.opsForSet().add(key, userId.toString());
        return result != null && result > 0;

    }
}




